package hu.mito.listviewbug;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListViewBugActivity extends Activity {
	
	private static final List<String> strings = new ArrayList<String>(10);

	private ArrayAdapter<String> adapter;
	
	private int repeatCount = 0;
	
	private Handler mHandler = new Handler();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ListView lv = (ListView) findViewById(R.id.listView1);
        
        adapter = new ArrayAdapter<String>(this, R.layout.listitem, strings);
        
        lv.setAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
    	android.view.MenuInflater menuInflater = getMenuInflater();
    	menuInflater.inflate(R.menu.main, menu);
    	
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// TODO Auto-generated method stub
    	switch (item.getItemId()) {
			case R.id.addten:
				mHandler.removeCallbacksAndMessages(null);
				repeatCount = 0;
	    		mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						if (repeatCount < 10) {
							repeatCount++;
							strings.add("ten "+Integer.toString(repeatCount));
							adapter.notifyDataSetChanged();
							mHandler.postDelayed(this, 1000);
						}
					}
				}, 1000);
				break;

			case R.id.addfive:
				mHandler.removeCallbacksAndMessages(null);
				repeatCount = 0;
	    		mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						if (repeatCount < 5) {
							repeatCount++;
							strings.add("five "+Integer.toString(repeatCount));
							adapter.notifyDataSetChanged();
							mHandler.postDelayed(this, 1000);
						}
					}
				}, 1000);
				break;
			case R.id.clear:
				strings.clear();
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
		}
    	
    	return super.onOptionsItemSelected(item);
    }
}